package bysj.dao;

import bysj.domain.*;
import bysj.domain.authority.Role;
import util.JdbcHelper;

import java.sql.*;
import java.util.*;

public class UserAssRoleDao {
    private static final UserAssRoleDao userAssRoleDao =
            new UserAssRoleDao();

    private UserAssRoleDao() {
    }

    public static UserAssRoleDao getInstance() {
        return userAssRoleDao;
    }
//    public void add(UserAssRole userAssRole, Connection conn) throws SQLException {
//        //预编译方式进行增加数据
//        String s = "insert into userassrole(user_id,role_id) value (?,?)";
//        PreparedStatement preparedStatement = conn.prepareStatement(s);
//        Map<User, Role> map = userAssRole.getMap();
//        for(User user:map.keySet()){
//            preparedStatement.setInt(1,user.getId());
//            preparedStatement.setInt(2,map.get(user).getId());
//            preparedStatement.executeUpdate();
//        }
//        //关闭连接
//        JdbcHelper.close(preparedStatement);
//    }


    public Collection<Role> find(Integer id, Connection conn) throws SQLException {
        Collection<Role> roles = new LinkedList<>();
        //预编译方式进行查询
        String s = "select * from userassrole where  user_id = ?";
        PreparedStatement preparedStatement = conn.prepareStatement(s);
        preparedStatement.setInt(1,id);
        ResultSet resultSet = preparedStatement.executeQuery();
        //将查询到的数据转为degree对象
        while (resultSet.next()){
            int role_id = resultSet.getInt(2);
            Role role = RoleDao.getInstance().find(conn,role_id);
            roles.add(role);
        }
        //关闭连接
        JdbcHelper.close(resultSet,preparedStatement);
        return roles;
    }
}